<template>
  <div class="app-container">
    <!-- 添加步骤条，当前激活步骤为3 -->
    <el-steps :active="3" finish-status="success" align-center>
      <el-step title="申请请假" />
      <el-step title="申请审批" />
      <el-step title="请假审批" />
    </el-steps>
    <div class="page-title">请假申请结果</div>

    <!-- 审批状态标签 -->
    <div class="status-tag">
      <el-tag :type="statusType" size="large">
        {{ form.approveResult }}
      </el-tag>
    </div>

    <!-- 老人基本信息 -->
    <el-card class="mt-4">
      <template #header><h3>老人基本信息</h3></template>
      <el-form label-width="120px" class="mt-2" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据编号">
              <el-input v-model="form.businessId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老人姓名">
              <el-input v-model="form.elderName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号">
              <el-input v-model="form.idCard" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="form.phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护理等级">
              <el-input v-model="form.nursingLevel" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位信息">
              <el-input v-model="form.bed" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护理员">
              <el-input v-model="form.nurse" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 请假申请信息 -->
    <el-card class="mt-4">
      <template #header><h3>请假申请信息</h3></template>
      <el-form label-width="120px" class="mt-2" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="陪同人类型">
              <el-input v-model="form.accompanyType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="陪同人姓名">
              <el-input v-model="form.accompanyName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="陪同人电话">
              <el-input v-model="form.accompanyPhone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假周期">
              <el-input v-model="form.leavePeriod" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计请假天数">
              <el-input v-model="form.expectedLeaveDays" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请假原因">
              <el-input
                v-model="form.leaveReason"
                type="textarea"
                rows="3"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人">
              <el-input v-model="form.applicant" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间">
              <el-input v-model="form.applyTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 审批结果信息 -->
    <el-card class="mt-4">
      <template #header><h3>审批信息</h3></template>
      <el-form label-width="120px" class="mt-2" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批结果">
              <el-input v-model="form.approveResult" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人">
              <el-input v-model="form.approverName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见">
              <el-input
                v-model="form.approveOpinion"
                type="textarea"
                rows="3"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间">
              <el-input v-model="form.approveTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作记录时间线 -->
    <el-card class="mt-4">
      <template #header><h3>操作记录</h3></template>
      <div v-if="operationRecords.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无操作记录" />
      </div>
      <el-timeline v-else>
        <el-timeline-item
          v-for="(item, index) in operationRecords"
          :key="index"
          :timestamp="formatTime(item.createTime)"
          :color="item.color"
        >
          <div>
            <strong>{{ item.operator }}</strong>
            <span class="ml-2">{{ item.content }}</span>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 操作按钮 -->
    <div class="mt-6 operate-btn">
      <el-button @click="goBack">返回列表</el-button>
      <el-button
        v-if="form.approveResult === '驳回'"
        type="primary"
        @click="goToEdit"
      >
        重新编辑申请
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElEmpty } from "element-plus";
// 路由实例
const router = useRouter();
const route = useRoute();

// 表单数据（不变）
const form = reactive({
  businessId: "",
  elderName: "",
  idCard: "",
  phone: "",
  nursingLevel: "",
  bed: "",
  nurse: "",
  accompanyType: "",
  accompanyName: "",
  accompanyPhone: "",
  leavePeriod: "",
  expectedLeaveDays: "",
  leaveReason: "",
  applicant: "",
  applyTime: "",
  approveResult: "",
  approverName: "",
  approveOpinion: "",
  approveTime: "",
});

const operationRecords = ref([]);
const loading = ref(false);

// 审批状态颜色（不变）
const statusType = computed(() => {
  switch (form.approveResult) {
    case "审批通过":
      return "success";
    case "审批拒绝":
      return "danger";
    case "驳回":
      return "warning";
    default:
      return "info";
  }
});

// 2. 新增：与 index.vue/index1.vue 完全一致的原生日期格式化函数
const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");
  const second = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};
// 转换审批状态文本（不变）
const getAuditStatusText = (status) => {
  const map = {
    1: "审批通过", // tinyint 1 → 文本"审批通过"
    2: "审批拒绝", // tinyint 2 → 文本"审批拒绝"
    3: "驳回", // tinyint 3 → 文本"驳回"
  };
  return map[status] || "未知状态";
};
// 页面加载：用原生 formatTime 替换所有 dayjs 调用
onMounted(async () => {
  try {
    loading.value = true;
    // 接收路由参数（不变）
    const {
      billNo,
      indexSubmitData: indexSubmitDataStr,
      indexBasicForm: indexBasicFormStr,
      indexApplyForm: indexApplyFormStr,
      approveData: approveDataStr,
      operationRecords: operationRecordsStr,
    } = route.query;
    // 校验参数（不变）
    if (
      !billNo ||
      !indexSubmitDataStr ||
      !approveDataStr ||
      !operationRecordsStr
    ) {
      ElMessage.error("缺少数据，无法展示审批结果");
      setTimeout(() => router.push("/leaveApplication/index"), 3000);
      return;
    }

    // 解析数据（不变）
    const indexSubmitData = JSON.parse(indexSubmitDataStr);
    const indexBasicForm = JSON.parse(indexBasicFormStr);
    const indexApplyForm = JSON.parse(indexApplyFormStr);
    const approveData = JSON.parse(approveDataStr);
    const records = JSON.parse(operationRecordsStr);
    const nurseNickName = indexSubmitData.nurseNickName;
    console.log(nurseNickName);
    console.log(approveData);
    // 3. 回显数据：用 formatTime 替换 dayjs 格式化
    // 基本信息（不变，仅时间字段用 formatTime）
    form.businessId = billNo;
    form.elderName = indexBasicForm.elderName || "";
    form.idCard = indexBasicForm.idCard || "";
    form.phone = indexBasicForm.phone || "";
    form.nursingLevel = indexBasicForm.nursingLevel || "无";
    form.bed = indexBasicForm.bed || "";
    const nurseUserName = indexSubmitData.nurseUserName || indexBasicForm.nurse;
    form.nurse = `${nurseUserName}、${approveData.approverName || ""}`;
    form.applicant = nurseNickName;

    // 申请信息：时间字段用 formatTime
    form.accompanyType = indexApplyForm.accompanyType || "无";
    form.accompanyName =
      indexApplyForm.accompanyType === "无"
        ? "无"
        : indexApplyForm.accompanyName || "无";
    form.accompanyPhone =
      indexApplyForm.accompanyType === "无"
        ? "无"
        : indexApplyForm.accompanyPhone || "无";
    form.leavePeriod = `${indexSubmitData.leaveStartTime || ""} —— ${
      indexSubmitData.expectedEndTime || ""
    }`;
    form.expectedLeaveDays = `${indexApplyForm.leaveDays || 0}天`;
    form.leaveReason = indexApplyForm.leaveReason || "";
    // 替换：用原生 formatTime 格式化申请时间
    form.applyTime = formatTime(indexSubmitData.createTime);
    form.approveResult = getAuditStatusText(approveData.auditStatus);
    form.approverName = approveData.approverName;
    form.approveOpinion = approveData.opinion || "";
    // 替换：用原生 formatTime 格式化审批时间
    form.approveTime = formatTime(approveData.createTime);

    // 操作记录：时间戳用 formatTime
    operationRecords.value = records
      .filter((item) => !item.content.includes("审批中")) // 移除“审批中”的记录
      .map((item) => ({
        ...item,
        operator:
          item.operator ||
          (item.content.includes("发起申请") ? nurseNickName : "护理组组长"),
        timestamp: formatTime(item.createTime),
      }));
  } catch (err) {
    console.error("解析数据失败：", err);
    ElMessage.error("数据解析异常，无法展示结果");
  } finally {
    loading.value = false;
  }
});

// 返回列表/重新编辑（不变）
const goBack = () => {
  router.push("/xietong/pendingTasks");
};
const goToEdit = () => {
  router.push({
    path: "/leaveApplication/index",
    query: {
      billNo: route.query.billNo,
      indexBasicForm: route.query.indexBasicForm,
      indexApplyForm: route.query.indexApplyForm,
    },
  });
};
</script>

<style scoped>
.page-title {
  font-size: 18px;
  font-weight: 700;
  color: #1f2329;
  margin-bottom: 20px;
}
.status-tag {
  margin-bottom: 20px;
  text-align: center;
}
.operate-btn {
  text-align: center;
  display: flex;
  gap: 16px;
  justify-content: center;
}
.el-timeline {
  padding: 20px;
}
.el-timeline-item {
  margin-bottom: 15px;
}
.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>
